package com.qingcloud.common.gateway.auth;


import com.qingcloud.base.api.remote.datafusion.DatafusionApi;
import com.qingcloud.base.pojo.ApiResult;
import com.qingcloud.base.remote.pojo.CustomerApiFunction;
import com.qingcloud.common.auth.service.impl.DefaultPermissionServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;

/**
 * url权限认证
 */
@Slf4j
@Component
public class PermissionAuthManager extends DefaultPermissionServiceImpl implements ReactiveAuthorizationManager<AuthorizationContext> {
    @Lazy
    @Resource
    private DatafusionApi datafusionApi;
    @Override
    public Mono<AuthorizationDecision> check(Mono<Authentication> authentication, AuthorizationContext authorizationContext) {
        return authentication.map(auth -> {
            ServerWebExchange exchange = authorizationContext.getExchange();
            ServerHttpRequest request = exchange.getRequest();
            boolean isPermission = super.hasPermission(auth, request.getMethodValue(), request.getURI().getPath());
            return new AuthorizationDecision(isPermission);
        }).defaultIfEmpty(new AuthorizationDecision(false));
    }
    @Override
    public List<CustomerApiFunction> findFuncByClientId(String clientId) {
        List<CustomerApiFunction> apiFunctions = null;
        ApiResult result = datafusionApi.getCustomerApiByClientId(clientId);
        if(result!=null) {
          apiFunctions =  (List<CustomerApiFunction>) result.getResult();
        }
        return apiFunctions;
    }
}
